using System.Xml.Xsl;
using Microsoft.VisualStudio.CodeCoverage;

namespace CoverageRunner
{
    public class CoverageReportCreator
    {
        private readonly string _vstsCoverageOutputFile;
        private readonly string _symbolsPath;
        private readonly string _exePath;
        private readonly string _coverageOutputXmlFilename;
        private readonly string _transformXsltFilename;
        private readonly string _transformOutputFilename;

        public CoverageReportCreator(string vstsCoverageOutputFile, string symbolsPath, string exePath, string coverageOutputXmlFilename, string transformXsltFilename, string transformOutputFilename)
        {
            _vstsCoverageOutputFile = vstsCoverageOutputFile;
            _symbolsPath = symbolsPath;
            _exePath = exePath;
            _coverageOutputXmlFilename = coverageOutputXmlFilename;
            _transformXsltFilename = transformXsltFilename;
            _transformOutputFilename = transformOutputFilename;
        }
  
        public void Create()
        {
            var coverageInfo = getCoverageInfo(_vstsCoverageOutputFile, _symbolsPath, _exePath);
            writeCoverageOutputAsXml(coverageInfo, _coverageOutputXmlFilename);
            writeCoverageOutputWithTransfrom(_coverageOutputXmlFilename, _transformXsltFilename, _transformOutputFilename);
        }

        private static CoverageInfo getCoverageInfo(string vstsCoverageOutputFile, string symbolsPath, string exePath)
        {
            CoverageInfoManager.SymPath = symbolsPath;
            CoverageInfoManager.ExePath = exePath;
            return CoverageInfoManager.CreateInfoFromFile(vstsCoverageOutputFile);
        }
 
        private static void writeCoverageOutputWithTransfrom(string coverageOutputXmlFilename, string transformXsltFilename, string transformOutputFilename)
        {
            var transformer = new XslCompiledTransform();
            transformer.Load(transformXsltFilename);
            transformer.Transform(coverageOutputXmlFilename, transformOutputFilename);
        }

        private static void writeCoverageOutputAsXml(CoverageInfo coverageInfo, string coverageOutputXmlFilename)
        {
            CoverageDS data = coverageInfo.BuildDataSet(null);
            data.ExportXml(coverageOutputXmlFilename);
        }

    }
}